//
//  LFHEncryptTool.m
//  LaiFengHui_App
//
//  Created by PF Z on 2018/8/6.
//  Copyright © 2018年 zengPengFei. All rights reserved.
//

#import "LFHEncryptTool.h"
#import "LFHRSA.h"
#import "LFHAes.h"
#import "NSString+Md5.h"
#import "GTMBase64.h"
//#import "LFHRsaInfoModel.h"
#import <MJExtension/MJExtension.h>

@implementation LFHEncryptTool

////获取RSA模型
//+(LFHRsaInfoModel *)RSAModel
//{
//    NSDictionary *dic=[SystemHelper getRSAInfoDic];
//    if (!dic) {
//        return nil;
//    }
//    
//    return [LFHRsaInfoModel mj_objectWithKeyValues:dic];
//}

//获取随机的16位AES密钥
+(NSString *)getAesRandomKey
{
    NSMutableString *key=[NSMutableString string];
    for (int i=0; i<16; i++) {
        int index=arc4random()%10;
        [key appendFormat:@"%d",index];
    }
    
    return key;
}

//字典转Json再加密
+(NSString *)PostEncryptWithParamDic:(NSDictionary *)dic
{
    NSString *jsonStr=[dic mj_JSONString];
    
    return [self PostEncryptWithString:jsonStr];
    
}

//字符串加密
+(NSString *)PostEncryptWithString:(NSString *)string
{
    NSString *randomKey=[self getAesRandomKey];
    
    // 第1部分 客户端随机生成的key通过RSA公钥加密，长度为172个字符
    NSString *partOne=[LFHRSA encryptString:randomKey publicKey:@""];
    
    // 第2部分 jsonContent 对称加密
    NSString *partTwo=[LFHAes encryptAESDataToBase64:string app_key:randomKey];
    
    // 第3部分 生成摘要，取前10位
    NSString *md5=[partTwo getMd5Str ];
    NSString *base64Str=[GTMBase64 stringByEncodingData:[md5 dataUsingEncoding:NSUTF8StringEncoding]];
    NSString *partThree=[base64Str substringToIndex:10];
    
    return [NSString stringWithFormat:@"%@%@%@",partOne,partTwo,partThree];
    
}

//解密字符串后转字典
+(NSDictionary *)PostDecryptToDicWithString:(NSString *)content
{
    NSString *desStr=[self PostDecryptToStringWithString:content];
    if (desStr==nil) {
        return nil;
    }
    
    return [desStr mj_JSONObject];
    
}

//解密字符串
+(NSString *)PostDecryptToStringWithString:(NSString *)content
{
    // RSA解密第一部分，获得Des的key
    NSString *partOne=[content substringToIndex:172];
    NSString *desKey=[LFHRSA decryptString:partOne privateKey:@""];
    if (desKey==nil || desKey.length==0) {
        return nil;
    }
    
    NSString *partTwo=[content substringWithRange:NSMakeRange(172, content.length-10-172)];
    NSString *partThree=[content substringFromIndex:content.length-10];

    NSString *decStr=[LFHAes decryptAESStringFromBase64:partTwo app_key:desKey];
    return decStr;

}

@end
